package cn.xinjiu.reggie.controller;

import cn.xinjiu.reggie.common.R;
import cn.xinjiu.reggie.entity.Employee;
import cn.xinjiu.reggie.service.EmployeeService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

/**
 * Created by xinchen on 2022/7/2
 *
 * @Description : employee controller
 */
@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    /**
     * @param request
     * @param employee
     * @return
     * @description login
     */
    @PostMapping("/login")
    public R<Employee> login(HttpServletRequest request, @RequestBody Employee employee) {

        String password = employee.getPassword();
        // 密码加密
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        // 包装查询对象
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername, employee.getUsername());
        Employee one = employeeService.getOne(queryWrapper);

        // 没有查询到则返回失败
        if (one == null) {
            return R.error("登录失败");
        }
        // 或密码不匹配也返回失败
        if (!one.getPassword().equals(password)) {
            return R.error("登录失败");
        }
        // 判断账号是否被禁用
        if (one.getStatus() == 0) {
            return R.error("账号已被禁用");
        }
        // success,input session
        request.getSession().setAttribute("employee", one.getId());

        return R.success(one);
    }

    /**
     * @param request
     * @return
     * @description logout
     */
    @PostMapping("/logout")
    public R logout(HttpServletRequest request) {
        request.getSession().removeAttribute("employee");
        return R.success("退出成功");
    }

    /**
     * @param employee
     * @return
     * @description 新增员工
     */
    @PostMapping
    public R<String> save(HttpServletRequest request, @RequestBody Employee employee) {
        log.info("新增员工：{}", employee.toString());

        // 设置加密密码
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));

        // create time
//        employee.setCreateTime(LocalDateTime.now());
        // update time
//        employee.setUpdateTime(LocalDateTime.now());
//        Long empId = (Long) request.getSession().getAttribute("employee");
        // create user id
//        employee.setCreateUser(empId);
        // update user id
//        employee.setUpdateUser(empId);
        // insert user



        employeeService.save(employee);

        return R.success("新增员工成功");
    }

    /**
     * @param page     当前页面
     * @param pageSize 每页显示条数
     * @param name     查询条件
     * @return 分页对象
     * @description 分页
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        log.info("page={}, pageSize={}, name={}", page, pageSize, name);

        // 分页构造器
        Page pageInfo = new Page(page, pageSize);
        // 条件构造器
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper();
        // 添加过滤条件
        queryWrapper.like(StringUtils.isNotEmpty(name), Employee::getName, name);
        // 添加排序条件
        queryWrapper.orderByDesc(Employee::getUpdateTime);
        // 执行查询
        employeeService.page(pageInfo, queryWrapper);

        return R.success(pageInfo);
    }

    /**
     * @param request 提供session
     * @param employee 提供员工对象
     * @return 更新结果
     * @description 根据ID更新员工信息
     *      Long型ID过长容易导致在处理时丢失数据精度。
     */
    @PutMapping
    public R<String> update(HttpServletRequest request, @RequestBody Employee employee) {
        log.info("更新员工：{}", employee.toString());

        // update time
//        employee.setUpdateTime(LocalDateTime.now());
        // update user
//        Long empId = (Long) request.getSession().getAttribute("employee");
//        employee.setUpdateUser(empId);

        long id = Thread.currentThread().getId();
        log.info("当前线程id为{}", id);

        // update
        employeeService.updateById(employee);
        return R.success("更新成功");
    }

    /**
     * @param id 员工ID
     * @return 查询结果
     * @description 根据id查询用户信息
     */
    @GetMapping("/{id}")
    public R<Employee> getById(@PathVariable Long id){
        log.info("根据ID查询员工：{}", id);
        Employee employee = employeeService.getById(id);
        if (employee != null) {
            return R.success(employee);
        }
        return R.error("查询失败");
    }

}
